<?php

namespace app\common\library;


use GuzzleHttp\Client;
use think\Exception;
use think\Log;

class TencentMap
{

    public static $config = [];

    public static $client;

    public static function instance()
    {
        self::$config = config('tencent_map');
        self::$client = new Client(config('tencent_map'));
        return new static();
    }

    private function getParams($params = [])
    {
        $params['key']    = self::$config['key'];
        $params['output'] = self::$config['output'];
        return $params;
    }

    /**
     * 批量距离计算
     * @param $params
     * @return array|mixed
     */
    public function matrix($params)
    {
        $data     = [
            'model' => $params['model'] ?? 'driving', // driving：驾车 walking：步行 bicycling：自行车
            'from'  => $params['from'], // 起点坐标 纬度,经度;纬度，经度 ,坐标间用英文分号分隔
            'to'    => $params['to'], // 终点点坐标 纬度,经度;纬度，经度 , 坐标间用英文分号分隔
        ];
        $query    = $this->getParams($data);
        $response = self::$client->get(self::$config['base_uri'] . '/ws/distance/v1/matrix', [
            'query'   => $query,
            'headers' => [],
        ]);
        return $this->resolve($response, __FUNCTION__);
    }

    /**
     * ip定位
     */
    public function ipLocation($params)
    {
        if (empty($params['ip'])) {
            throw new Exception('请输入ip');
        }
        $params   = $this->getParams($params);
        $response = self::$client->get(self::$config['base_uri'] . '/ws/location/v1/ip', [
            'query'   => $params,
            'headers' => [],
        ]);
        return $this->resolve($response, __FUNCTION__);
    }

    /**
     * 坐标获取地址
     */
    public function geocoder($params)
    {
        if (empty($params['location'])) {
            throw new Exception('请输入location');
        }
        $params   = $this->getParams($params);
        $response = self::$client->get(self::$config['base_uri'] . '/ws/geocoder/v1/', [
            'query'   => $params,
            'headers' => [],
        ]);
        return $this->resolve($response, __FUNCTION__);
    }

    public function resolve($response, $action)
    {
        $responseJson = json_decode($response->getBody(), true);
        if (!$responseJson) {
            $this->writeLog('请求腾讯地图接口失败', $action);
            return [];
        }
        if ($responseJson['status'] != 0) {
            $this->writeLog($responseJson['message'], $action);
            return [];
        }
        return $responseJson['result'];
    }

    private function writeLog($error, $function = "")
    {
        $error = json_encode($error, JSON_UNESCAPED_UNICODE);
        Log::error("地图接口失败：func:{$function} ;" . $error);
    }
}